<?php
header("Content-Type: application/json; charset=utf-8");
session_start();
require_once '../config/db.php';
$action = $_GET['action'] ?? '';

// 验证管理员权限
function checkAdmin() {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
        echo json_encode(['status' => 'error', 'message' => '无权限']);
        exit;
    }
}

// 获取用户列表
if ($action === 'list') {
    checkAdmin();
    try {
        $stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
        $users = $stmt->fetchAll();
        echo json_encode(['status' => 'success', 'data' => $users]);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// 添加用户
if ($action === 'add') {
    checkAdmin();
    $data = json_decode(file_get_contents('php://input'), true);
    // 验证用户名
    if (strlen($data['username']) < 3) {
        echo json_encode(['status' => 'error', 'message' => '用户名至少3位']);
        exit;
    }
    // 验证密码
    if (strlen($data['password']) < 6) {
        echo json_encode(['status' => 'error', 'message' => '密码至少6位']);
        exit;
    }
    // 检查用户名是否存在
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username=?");
    $stmt->execute([$data['username']]);
    if ($stmt->fetch()) {
        echo json_encode(['status' => 'error', 'message' => '用户名已存在']);
        exit;
    }
    // 添加用户
    try {
        $password = password_hash($data['password'], PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, password, email, phone, role, reg_time) 
                              VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([
            $data['username'], $password, $data['email'], $data['phone'], $data['role']
        ]);
        echo json_encode(['status' => 'success', 'message' => '添加成功']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// 编辑用户
if ($action === 'edit') {
    checkAdmin();
    $id = $_GET['id'] ?? 0;
    $data = json_decode(file_get_contents('php://input'), true);
    try {
        $sql = "UPDATE users SET email=?, phone=?, role=?, status=? WHERE id=?";
        $params = [$data['email'], $data['phone'], $data['role'], $data['status'], $id];
        // 如果有密码则更新
        if ($data['password']) {
            $sql = "UPDATE users SET email=?, phone=?, role=?, status=?, password=? WHERE id=?";
            $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        echo json_encode(['status' => 'success', 'message' => '编辑成功']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// 更改用户状态（封禁/解封）
if ($action === 'change_status') {
    checkAdmin();
    $data = json_decode(file_get_contents('php://input'), true);
    try {
        $stmt = $pdo->prepare("UPDATE users SET status=? WHERE id=?");
        $stmt->execute([$data['status'], $data['user_id']]);
        echo json_encode(['status' => 'success', 'message' => '状态更新成功']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// 删除用户
if ($action === 'delete') {
    checkAdmin();
    $id = $_GET['id'] ?? 0;
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode(['status' => 'success', 'message' => '删除成功']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['status' => 'error', 'message' => '无效操作']);